package com.tanhua.dubbo.server.api;

import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.UserLocation;
import com.tanhua.dubbo.server.vo.UserLocationVo;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metric;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;


/*
    更新地理位置
 */
@Service(version = "1.0.0")
public class UserLocationApiImpl implements UserLocationApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 更新用户地理位置
     *
     * @param userId    用户id
     * @param longitude 经度
     * @param latitude  维度
     * @param address   位置
     * @return
     */
    @Override
    public String updateUserLocation(Long userId, Double longitude, Double latitude, String address) {
        //创建UserLocation用户 封装参数
        UserLocation userLocation = new UserLocation();
        userLocation.setAddress(address);
        userLocation.setUserId(userId);
        userLocation.setLocation(new GeoJsonPoint(longitude, latitude));

        //查询用户的地理位置
        Query query = Query.query(Criteria.where("userId").is(userId));
        UserLocation ul = mongoTemplate.findOne(query, UserLocation.class);

        //如果获取到的ul为空,则说明mongodb中没有值,
        if (null == ul) {
            //新增用户位置数据
            userLocation.setId(ObjectId.get());
            userLocation.setCreated(System.currentTimeMillis());
            userLocation.setUpdated(userLocation.getCreated());
            userLocation.setLastUpdated(userLocation.getCreated());

            mongoTemplate.save(userLocation);

            return userLocation.getId().toHexString();  //返回位置对象的objectId

        } else {  //不为空,更新数据
            Update update = Update.update("location", userLocation.getLocation())  //位置坐标
                    .set("updated", System.currentTimeMillis())  //当前更新的时间
                    .set("lastUpdated", ul.getUpdated())  //上一次更新的时间
                    .set("address", userLocation.getAddress()); //位置

            mongoTemplate.updateFirst(query, update, UserLocation.class);
        }

        return ul.getId().toHexString(); //返回位置对象的objectId
    }

    /**
     * 查询地理位置
     *
     * @param userId
     * @return
     */
    @Override
    public UserLocationVo queryByUserId(Long userId) {
        Query query = Query.query(Criteria.where("userId").is(userId));
        UserLocation location = mongoTemplate.findOne(query, UserLocation.class);
        return UserLocationVo.format(location);
    }


    /**
     * 根据地理位置查询用户
     *
     * @param longitude
     * @param latitude
     * @param range
     * @return
     */
    @Override
    public List<UserLocationVo> queryUserFromLocation(Double longitude, Double latitude, Integer range) {
        //确定中心点
        GeoJsonPoint geoJsonPoint = new GeoJsonPoint(longitude, latitude);

        //确定半径  转换为2dsphere的距离
        Distance distance = new Distance(range / 1000, Metrics.KILOMETERS);

        //画一个圆
        //创建圆的对象
        Circle circle = new Circle(geoJsonPoint, distance);
        Query query = Query.query(Criteria.where("location").withinSphere(circle));
        return UserLocationVo.formatToList(mongoTemplate.find(query, UserLocation.class));
    }
}
